<script setup lang="ts">
import { LoginForm } from "@/types/user";
import { Toast } from "vant";
import useStore from "@/store";
import { useRoute } from "vue-router";
import router from "@/router";
const route = useRoute();
const loginForm: LoginForm = {
    mobile: "13912345678",
    code: "246810",
};
console.log(route);

const login = async () => {
    const { user } = useStore();
    Toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0, // 持续展示toast，永远不会关闭
        overlay: true, // 整体加个遮罩
    });
    try {
        console.log(route, router);
        await user.login(loginForm);
        const backto = (route.query.backto as string) || "/";
        router.push(backto);
        Toast.success("success");
    } catch (error) {
        console.log(error);
        // 一个页面上只能有一个toast，它会把上面的loading状态覆盖掉
        Toast.fail("验证码错误");
    }
};
</script>
<template>
    <div class="login">
        <van-nav-bar
            title="用户登录"
            left-text="返回"
            left-arrow
            @click-left="$router.back()"
        />
        <van-form @submit="login">
            <van-field
                v-model="loginForm.mobile"
                name="手机号"
                label="手机号"
                placeholder="手机号"
                :rules="[
                    {
                        required: true,
                        message: '请填写手机号',
                        trigger: 'onBlur',
                    },
                    {
                        pattern: /^1[3-9]\d{9}$/,
                        message: '请输入正确的11位手机号码',
                        trigger: 'onChange',
                    },
                ]"
            />
            <van-field
                v-model="loginForm.code"
                type="password"
                name="密码"
                label="密码"
                placeholder="密码"
                :rules="[
                    {
                        required: true,
                        message: '请输入验证码',
                        trigger: 'onBlur',
                    },
                    {
                        pattern: /^\d{6}$/,
                        message: '请输入6位验证码',
                        trigger: 'onChange',
                    },
                ]"
            />
            <div class="btn-wrap" style="margin: 16px">
                <van-button block type="primary" native-type="submit"
                    >登录</van-button
                >
            </div>
        </van-form>
    </div>
</template>

<style lang="scss" scoped>
.login {
    .btn-wrap {
        padding: 20px;
        .van-button {
            width: 100%;
            color: #fff;
            background-color: #07c160;
            border-radius: 5px;
        }
    }
}
</style>
